package B1;

import java.util.HashMap;
import java.util.Map;

// 恒温水箱状态机
public class TankStateMachine {
    private TankState currentState;
    // 状态转移表：当前状态 → (事件 → 下一个状态)
    private final Map<TankState, Map<TankEvent, TankState>> transitions;

    public TankStateMachine() {
        // 初始状态为继电器关闭
        this.currentState = TankState.RELAY_OFF;
        this.transitions = new HashMap<>();
        initTransitions();
    }

    // 初始化状态转移规则（对应状态图逻辑）
    private void initTransitions() {
        // 1. 继电器关闭状态（RELAY_OFF）的转移规则
        Map<TankEvent, TankState> relayOffTransitions = new HashMap<>();
        relayOffTransitions.put(TankEvent.TEMP_BELOW_20_WITH_WATER, TankState.RELAY_ON);
        relayOffTransitions.put(TankEvent.TEMP_BELOW_20_WITHOUT_WATER, TankState.RELAY_OFF);
        relayOffTransitions.put(TankEvent.TIME_23_00, TankState.SLEEP);
        transitions.put(TankState.RELAY_OFF, relayOffTransitions);

        // 2. 继电器开启状态（RELAY_ON）的转移规则
        Map<TankEvent, TankState> relayOnTransitions = new HashMap<>();
        relayOnTransitions.put(TankEvent.TEMP_REACH_100, TankState.RELAY_OFF);
        relayOnTransitions.put(TankEvent.TIME_23_00, TankState.SLEEP);
        relayOnTransitions.put(TankEvent.TANK_BROKEN, null); // 烧坏后无后续状态（终止）
        transitions.put(TankState.RELAY_ON, relayOnTransitions);

        // 3. 休眠状态（SLEEP）的转移规则
        Map<TankEvent, TankState> sleepTransitions = new HashMap<>();
        sleepTransitions.put(TankEvent.TIME_07_00, TankState.RELAY_OFF);
        transitions.put(TankState.SLEEP, sleepTransitions);
    }

    // 处理事件并转移状态
    public void handleEvent(TankEvent event) {
        Map<TankEvent, TankState> eventMap = transitions.get(currentState);
        if (eventMap == null || !eventMap.containsKey(event)) {
            System.out.println("当前状态[" + currentState + "]不支持事件[" + event + "]");
            return;
        }

        TankState nextState = eventMap.get(event);
        if (nextState == null) {
            System.out.println("状态转移：" + currentState + " → 水箱烧坏（终止）");
            currentState = null; // 标记为终止状态
        } else {
            System.out.println("状态转移：" + currentState + " → " + nextState + "（事件：" + event + "）");
            currentState = nextState;
        }
    }

    // 获取当前状态
    public TankState getCurrentState() {
        return currentState;
    }
}